package org.weed.gadgets.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.imageio.ImageIO;

public class ByteUtils {
    public static final char[] HEX_DIGITS = {
        '0', '1', '2', '3', '4', '5', '6', '7',
           '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };
    
	public static String toHexString(char c) {
		byte high = (byte) (c >>> 8);
		byte low = (byte) (c & 0xff);
		return new String(toHex(high)) + new String(toHex(low));
	}
	
    public static String toHex(byte[] bytes) {
    	return toHex(bytes, 0, bytes.length);
    }
    
    public static String toHex(byte[] bytes, int from, int length) {
    	length = length << 1;
    	char[] hex = new char[length];
        int index = 0;
    	for (int i = from; index < length; i++) {
    		hex[index++] = HEX_DIGITS[(0xF0 & bytes[i]) >>> 4 ];
    		hex[index++] = HEX_DIGITS[ 0x0F & bytes[i] ];
    	}
    	return new String(hex);   	
    }
    
	// ========== Other -> HexString
	public static String toHex(byte b) {
		return toHex(new byte[] {b});
	}
	

	

	
	// ========== Other -> Bytes
	public static byte[] toBytes(int value) {
		return ByteBuffer.allocate(4).putInt(value).array();
	}
	
	public static byte[] toBytes(BufferedImage bufferedImage) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "png", baos);
		baos.flush();
		byte[] bytes = baos.toByteArray();
		baos.close();
		return bytes;
	}
	
	// ========== Bytes -> Other
	public static int toInt(byte[] bytes) {
		return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff); 
	}
	
	public static BufferedImage toBufferedImage(byte[] bytes) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		return ImageIO.read(bais);
	}
	
	// ========== Byte Array
	public static void reverse(byte[] bytes) {
		try {
			byte temp;
			int length = bytes.length;
			for (int i=0; i<length/2; i++) {
				temp = bytes[i];
				bytes[i] = bytes[length-1-i];
				bytes[length-1-i] = temp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// ==========
	public static void printBytes(byte[] bytes) {
		StringBuilder builder = new StringBuilder();
		builder.append("0x");
	    for (int i = 0; i < bytes.length; i++) {
	        builder.append(toHex(bytes[i]));
	    }
	    System.out.println(builder.toString());
	}	
	
	public static void main(String[] args) {
		byte[] bytes = new byte[] {(byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd};
		ByteUtils.printBytes(bytes);
		ByteUtils.reverse(bytes);
		ByteUtils.printBytes(bytes);
	}
	
}
